using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Reactive.Linq;

namespace Clancy.Service.Base
{
    internal class CommunicationServiceBase : IDisposable
    {
        protected readonly List<IDisposable> Disposables = new List<IDisposable>();

        public virtual void Dispose()
        {
            foreach (IDisposable disp in Disposables)
            {
                disp.Dispose();
            }
            Disposables.Clear();
        }

        protected void AttachToCollection<T>(ObservableCollection<T> collectionToObserve, Action<IList> addedAction, Action<IList> removedAction)
        {
            var surveilanceCollectionChangedObservable =
                Observable.FromEventPattern<NotifyCollectionChangedEventArgs>(collectionToObserve, "CollectionChanged");

            Disposables.Add(surveilanceCollectionChangedObservable
                .Where(change => change.EventArgs.Action == NotifyCollectionChangedAction.Add)
                .Select(change => change.EventArgs.NewItems)
                .Subscribe(addedAction));

            Disposables.Add(surveilanceCollectionChangedObservable
                .Where(change => change.EventArgs.Action == NotifyCollectionChangedAction.Remove)
                .Select(change => change.EventArgs.OldItems)
                .Subscribe(removedAction));
        }
    }
}